﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Epm.AppLogic.Framework;
using msBsc.Xsd.DataTds;
using System.Data;

namespace msBsc.AppLogic.DataAlc
{
    public class CBizShpCommercialTenantInfo : CustBizObject
    {
        private CDmShpCommercialTenantInfo m_CDmShpCommercialTenantInfo = new CDmShpCommercialTenantInfo();
        private CDmShpCommercialTenantInfo oDmShpCommercialTenantInfo
        {
            get { return m_CDmShpCommercialTenantInfo; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CBizShpCommercialTenantInfo()
            : base()
        {
            this.DataObj = new CDbAccess();
            this.DataObj.Init(this.m_CDmShpCommercialTenantInfo.SHP_COMMERCIAL_TENANT_INFO);
            this.TableName = this.DataObj.TableName;
            this.DataObj.KeyField = this.DataObj.Fields["COMM_TENANT_ID"];
            //this.DataObj.IdGroup = "RID";
        }

        /// <summary>
        /// 新增记录前的处理
        /// </summary>
        /// <param name="drw">新增数据行</param>
        /// <returns>true/false</returns>
        /// <remarks>
        /// 生成ID值
        /// </remarks>
        protected override bool BeforeRowAdded(DataRow drw)
        {
            if (drw[this.KeyFieldName].ToString().Length < 10)
            {
                drw[this.KeyFieldName] = msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
            }
            drw["SCORE_QTY"] = 0;
            drw["CHARGE_AMT"] = 0;
            drw["DEPOSIT_AMT"] = 0;
            drw["MALL_SID_01"] = "";
            drw["MALL_SID_02"] = ""; 
            //drw["LOGIN_PSWD"] = msBsc.AppLogic.Cfg.DesCry.encMe("123456", "zbhpass");

            AddDepositAmtPayTradingLog(drw);
            return true;
        }

        /// <summary>
        /// 记录修改前检验
        /// </summary>
        /// <param name="drw">当前记录</param>
        /// <returns>>校验合法，返回值为true,否则返回false</returns>
        /// <remarks>
        /// ID不允许修改,并把此修改操作记录到BSE_MODIFY_HISTORY表中
        /// </remarks>
        protected override bool BeforeRowModified(DataRow drw)
        {
            //ID不容许修改
            if (drw[this.KeyFieldName].ToString() != drw[this.KeyFieldName, DataRowVersion.Original].ToString())
            {
                Exception e = new Exception(this.TableName + "表的主键" + this.KeyFieldName + "字段不允许被修改");
                throw e;
            }
            return true;
        }

        protected override bool BeforeRowDeletedR(DataRow drw)
        {
            //using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo objtem = new CBizShpGoodsInfo())
            //{
            //    DataSet ds = objtem.SelectByDealerId(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //}
            //using (msBsc.AppLogic.DataAlc.CBizShpCommercialHeadImg objtem = new CBizShpCommercialHeadImg())
            //{
            //    DataSet ds = objtem.SelectByDealerId(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //}
            //using (msBsc.AppLogic.DataAlc.CBizShpCommercialLogisticsZone objtem = new CBizShpCommercialLogisticsZone())
            //{
            //    DataSet ds = objtem.SelectByDealerId(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //}
            //using (msBsc.AppLogic.DataAlc.CBizShpCommercialLogistics objtem = new CBizShpCommercialLogistics())
            //{
            //    DataSet ds = objtem.SelectByDealerId(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //}
            //using (msBsc.AppLogic.DataAlc.CBizShpCommercialPageColumnItem objtem = new CBizShpCommercialPageColumnItem())
            //{
            //    DataSet ds = objtem.SelectByDealerId(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //}
            //using (msBsc.AppLogic.DataAlc.CBizShpCommercialPageColumn objtem = new CBizShpCommercialPageColumn())
            //{
            //    DataSet ds = objtem.SelectByShopId(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //}
            //using (msBsc.AppLogic.DataAlc.CBizShpCommercialShipping objtem = new CBizShpCommercialShipping())
            //{
            //    DataSet ds = objtem.SelectByDealerId(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //}
            return true;
        }

        protected override bool AfterRowAdded(DataRow drw)
        {
            return true;
        }

        /// <summary>
        /// 校验商家是否允许发布商品
        /// </summary>
        /// <param name="strShopId"></param>
        /// <returns></returns>
        public string ValitPubGoods(string strShopId,string strShopSt,string strDepAmt)
        {
            if (strShopSt == string.Empty || strDepAmt == string.Empty)
            {
                DataSet ds = this.DataObj.QueryBySQL("SELECT COMM_TENANT_SID,DEPOSIT_AMT FROM SHP_COMMERCIAL_TENANT_INFO WHERE COMM_TENANT_ID='" + strShopId + "'");
                if (ds.Tables[0].Rows.Count <= 0)
                {
                    return "商家不存在！";
                }
                strShopSt = ds.Tables[0].Rows[0]["COMM_TENANT_SID"].ToString();
                strDepAmt = ds.Tables[0].Rows[0]["DEPOSIT_AMT"].ToString();
            }




            if (strShopSt == "4")
            {
                return "该店铺已关闭！";
            }
            if (strShopSt == "3")
            {
                return "开店申请已被拒绝！";
            }
            if (strShopSt != "2")
            {
                return "商家开店申请未正式获得审核批准！";
            }

            string strDepLimit = msBsc.AppLogic.Cfg.SystemSet.oSystemSet.getSysSetVal("_SHOP_DEPOSIT_LIMIT");
            if (strDepLimit == "1")
            {
                if (decimal.Parse(strDepAmt)<=0M)
                {
                    return "商家未缴纳保证金，不允许进行商品发布和交易！";
                }
            }

            return "";
        }

        /// <summary>
        /// 增加保证金缴费付款记录
        /// </summary>
        /// <param name="drw"></param>
        /// <returns></returns>
        public string AddDepositAmtPayTradingLog(DataRow drw)
        {
            using (CBizShpChargeTradingLog objcharg = new CBizShpChargeTradingLog())
            {
                decimal decamt = msBsc.AppLogic.Cfg.SystemSet.oSystemSet.getSysSetVal<decimal>("_SHOP_DEPOSIT_AMT");
                DataRow drlog = objcharg.AddTradingLogForJiaofei(decamt.ToString(), drw["COMM_TENANT_ID"].ToString(), drw["COMM_TENANT_NME"].ToString(), "1"
                    , "缴纳保证金"
                    , "UPDATE SHP_COMMERCIAL_TENANT_INFO SET DEPOSIT_AMT=" + decamt.ToString() + " WHERE COMM_TENANT_ID='" + drw["COMM_TENANT_ID"].ToString() + "'");

                drw["DEPOSIT_TRADING_NO"] = drlog["TRADING_NO"];
                return drlog["TRADING_NO"].ToString();
            }
        }

        public DataSet SelectByIds(string strIdS)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE  " + this.KeyFieldName + " IN  ('" + strIdS.Replace("'", "").Replace(",", "','") + "')");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectUserLedgerStatistic(string strDealerId)
        {
            DataSet ds = this.DataObj.QueryBySQL(@"
    SELECT    
     WAIT_PAY_COUNT =SUM(CASE WHEN A.TRADING_SID IS NOT NULL AND A.TRADING_SID='待支付' THEN 1 ELSE 0 END)
    ,COMP_PAY_COUNT=SUM(CASE WHEN A.TRADING_SID IS NOT NULL AND A.TRADING_SID='已支付' THEN 1 ELSE 0 END) 
    ,CAC_PAY_COUNT=SUM(CASE WHEN A.TRADING_SID IS NOT NULL AND A.TRADING_SID='已取消' THEN 1 ELSE 0 END) 
    ,PAY_COUNT =COUNT(*)
    FROM SHP_CHARGE_TRADING_LOG A
    WHERE
     ( A.ACCOUNT_NO='" + strDealerId + @"' )
");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }
        public decimal GetShopChargeAmt(string strDealerId)
        {
            DataSet ds = this.DataObj.QueryBySQL(@"
    SELECT
    CHARGE_AMT= ISNULL(B.CHARGE_AMT,0.00) 
    FROM SHP_COMMERCIAL_TENANT_INFO B WHERE B.COMM_TENANT_ID='" + strDealerId + "' ");
            if (ds.Tables[0].Rows.Count > 0 )
            {
                return (decimal)ds.Tables[0].Rows[0]["CHARGE_AMT"];
            }
            return 0M;
        }

        /// <summary>
        /// 获取被锁定积分
        /// </summary>
        /// <param name="strDealerId"></param>
        /// <returns></returns>
        public int GetShopScoreFreezeQty(string strDealerId)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT SCORE_FREEZE_QTY=ISNULL(SUM(ISNULL(B.GOODS_ACT_QTY,0)*ISNULL(A.SCORE_NUM,0)),0) FROM SHP_GOODS_INFO A LEFT OUTER JOIN SHP_GOODS_NORMS_PUBLIC B ON A.GOODS_ID=B.GOODS_ID WHERE A.COMM_TENANT_ID<>'' AND A.COMM_TENANT_ID='" + strDealerId + @"' ");
            if (ds.Tables[0].Rows.Count > 0)
            {
                return (int)ds.Tables[0].Rows[0]["SCORE_FREEZE_QTY"];
            }
            return 0;
        }
        /// <summary>
        /// 获取可用积分
        /// </summary>
        /// <param name="strDealerId"></param>
        /// <returns></returns>
        public int GetShopScoreAllowUseQty(string strDealerId)
        {
            DataSet ds = this.DataObj.QueryBySQL(@"
    SELECT
    SCORE_QTY= (ISNULL(B.SCORE_QTY,0)-ISNULL(V1.SCORE_FREEZE_QTY,0))
    FROM 
    (
    SELECT A.COMM_TENANT_ID,SCORE_FREEZE_QTY=SUM(ISNULL(B.GOODS_ACT_QTY,0)*ISNULL(A.SCORE_NUM,0)) FROM SHP_GOODS_INFO A LEFT OUTER JOIN SHP_GOODS_NORMS_PUBLIC B ON A.GOODS_ID=B.GOODS_ID WHERE A.COMM_TENANT_ID<>'' AND A.COMM_TENANT_ID='" + strDealerId + @"' GROUP BY A.COMM_TENANT_ID
    ) AS V1
    LEFT OUTER JOIN SHP_COMMERCIAL_TENANT_INFO B ON V1.COMM_TENANT_ID=B.COMM_TENANT_ID
    ");
            if (ds.Tables[0].Rows.Count > 0 )
            {
                return (int)ds.Tables[0].Rows[0]["SCORE_QTY"];
            }
            return 0;
        }

//        public void UpdateScoreFreezeQty(string strDealerId)
//        {
//            this.DataObj.ExecuteBySQL(@"
//    UPDATE B SET 
//    SCORE_FREEZE_QTY=V1.SCORE_FREEZE_QTY
//    FROM 
//    (
//    SELECT A.COMM_TENANT_ID,SCORE_FREEZE_QTY=SUM(ISNULL(B.GOODS_ACT_QTY,0)*ISNULL(A.SCORE_NUM,0)) FROM SHP_GOODS_INFO A LEFT OUTER JOIN SHP_GOODS_NORMS_PUBLIC B ON A.GOODS_ID=B.GOODS_ID WHERE A.COMM_TENANT_ID<>'' AND A.COMM_TENANT_ID='" + strDealerId + @"' GROUP BY A.COMM_TENANT_ID
//    ) AS V1
//    LEFT OUTER JOIN SHP_COMMERCIAL_TENANT_INFO B ON V1.COMM_TENANT_ID=B.COMM_TENANT_ID
//    ");
//        }
         
        public DataSet SelectCommercialTenantInfo(string strCommTenant, string strStatus)
        {
            string strsql = "SELECT B.E_MAIL,B.TEL,A.*,COMM_TYPE_TXT=CASE WHEN COMM_TYPE_CID='2' THEN '企业' ELSE '个人' END FROM " + this.TableName + " A LEFT OUTER JOIN SYS_USER B ON A.USER_NME=B.USER_NME WHERE  A.COMM_TENANT_NME LIKE  '%" + strCommTenant + "%'";
            if (!string.IsNullOrEmpty(strStatus))
            {
                strsql += " AND (COMM_TENANT_SID='" + strStatus + "')";
            }
            DataSet ds = this.DataObj.QueryBySQL(strsql);
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectCommercialTenantInfo(string strId)
        {
            string strsql = "SELECT *,COMM_TYPE_TXT=CASE WHEN COMM_TYPE_CID='2' THEN '企业' ELSE '个人' END FROM " + this.TableName + " WHERE  COMM_TENANT_ID ='" + strId + "'";
            DataSet ds = this.DataObj.QueryBySQL(strsql);
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectByUserNme(string strUserNme)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE  USER_NME =  '" + strUserNme + "'");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        /// <summary>
        /// 获取店铺统计信息
        /// </summary>
        /// <param name="strDealerI"></param>
        /// <returns></returns>
        public DataSet SelectSolpStatistic(string strDealerId)
        {
            DataSet ds = this.DataObj.QueryBySQL(@"
    SELECT    
     WAIT_PAY_COUNT =SUM(CASE WHEN A.TRADE_STATUS_TXT IS NOT NULL AND A.TRADE_STATUS_TXT='等待买家付款' THEN 1 ELSE 0 END)
    ,WAIT_SHIPPING_COUNT=SUM(CASE WHEN A.TRADE_STATUS_TXT IS NOT NULL AND A.TRADE_STATUS_TXT='买家已付款' THEN 1 ELSE 0 END)
    ,WAIT_RECEIPT_COUNT=SUM(CASE WHEN A.TRADE_STATUS_TXT IS NOT NULL AND A.TRADE_STATUS_TXT='卖家已发货' THEN 1 ELSE 0 END)
    ,WAIT_RETURN_COUNT=SUM(CASE WHEN A.TRADE_STATUS_TXT IS NOT NULL AND A.TRADE_STATUS_TXT='退款中的订单' THEN 1 ELSE 0 END)
    ,WAIT_REVIEW_COUNT =SUM(CASE WHEN A.SELLER_RATE_SID='0' THEN 1 ELSE 0 END)
    FROM SHP_ORDER_FORM A
    WHERE
    (A.TRADE_STATUS_TXT='等待买家付款' OR A.TRADE_STATUS_TXT='退款中的订单' OR A.TRADE_STATUS_TXT='买家已付款' OR A.TRADE_STATUS_TXT='卖家已发货' OR A.SELLER_RATE_SID='0') AND  (A.COMM_TENANT_ID='" + strDealerId + @"' )
");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectShopOrderStaticsInfo(string strDealerId)
        {
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("strDealerId", ParameterDirection.Input, EDbType.String, 36, strDealerId));
            DataSet ds = this.DataObj.QueryBySP("SHP_SELECT_SHOP_ORDER_STATICS_INFO", parmCollection);
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }




        public string GetHeadJsonData(string strDealerId, DataRow drDealer)
        {
            if (drDealer == null)
            {
                DataSet dstem1 = this.SelectById(strDealerId);
                if (dstem1.Tables[0].Rows.Count > 0)
                {
                    drDealer = dstem1.Tables[0].Rows[0];
                }
                else
                {
                    return "{}";
                }
            }
            DataSet ds1 = this.DataObj.QueryBySQL("SELECT CT_LEVEL_ONE_ID,CT_LEVEL_ONE_NME FROM SHP_COMMERCIAL_GOODS_LEVEL_ONE WHERE COMM_TENANT_ID='" + strDealerId + "'");
            DataSet ds2 = this.DataObj.QueryBySQL("SELECT CT_LEVEL_TWO_ID,CT_LEVEL_TWO_NME,CT_LEVEL_ONE_ID FROM SHP_COMMERCIAL_GOODS_LEVEL_TWO WHERE COMM_TENANT_ID='" + strDealerId + "'");
            DataSet ds3 = this.DataObj.QueryBySQL("SELECT CT_LEVEL_THREE_ID,CT_LEVEL_THREE_NME,CT_LEVEL_TWO_ID FROM SHP_COMMERCIAL_GOODS_LEVEL_THREE WHERE COMM_TENANT_ID='" + strDealerId + "'");
            DataSet dsimg = this.DataObj.QueryBySQL("SELECT SEQ_NUM,IMG_URL,BG_COLOR,LINK_URL FROM SHP_COMMERCIAL_HEAD_IMG WHERE COMM_TENANT_ID='" + strDealerId + "' ORDER BY SEQ_NUM ASC ");

            System.Text.StringBuilder sbRet = new System.Text.StringBuilder();
            sbRet.Append("{");
            sbRet.Append("\"shop_id\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(strDealerId) + "\"");
            if (drDealer["HEADER_SHOW_SHOP_NME"].ToString() == "True")
            {
                sbRet.Append(",\"shop_name\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(drDealer["COMM_TENANT_NME"].ToString()) + "\"");
            }
            else
            {
                sbRet.Append(",\"shop_name\":\"\"");
            }
            sbRet.Append(",\"logo_url\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(drDealer["LOGO_IMG_URL"].ToString()) + "\"");
            sbRet.Append(",\"head_img_url\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(drDealer["DEFAULT_HEADER_IMG_URL"].ToString()) + "\"");
            sbRet.Append(",\"head_bg_color\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(drDealer["DEFAULT_HEADER_BG_COLOR"].ToString()) + "\"");

            sbRet.Append(",\"img_count\":" + dsimg.Tables[0].Rows.Count.ToString() + ",imgrows:[");
            for (int a = 0; a < dsimg.Tables[0].Rows.Count; a++)
            {
                if (a > 0)
                {
                    sbRet.Append(",");
                }
                sbRet.Append("{");
                sbRet.Append("\"seq_num\":" + dsimg.Tables[0].Rows[a]["SEQ_NUM"].ToString() + "");
                sbRet.Append(",\"img_url\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(dsimg.Tables[0].Rows[a]["IMG_URL"].ToString()) + "\"");
                sbRet.Append(",\"bg_color\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(dsimg.Tables[0].Rows[a]["BG_COLOR"].ToString()) + "\"");
                sbRet.Append(",\"link_url\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(dsimg.Tables[0].Rows[a]["LINK_URL"].ToString()) + "\"");

                sbRet.Append("}");
            }
            sbRet.Append("]");


            sbRet.Append(",\"r_count\":" + ds1.Tables[0].Rows.Count.ToString() + ",rows:[");
            for (int a = 0; a < ds1.Tables[0].Rows.Count; a++)
            {
                if (a > 0)
                {
                    sbRet.Append(",");
                }
                sbRet.Append("{");
                sbRet.Append("\"ID\":\"" + ds1.Tables[0].Rows[a]["CT_LEVEL_ONE_ID"].ToString() + "\"");
                sbRet.Append(",\"NAME\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(ds1.Tables[0].Rows[a]["CT_LEVEL_ONE_NME"].ToString()) + "\"");

                DataRow[] arrrow1 = ds2.Tables[0].Select("CT_LEVEL_ONE_ID='" + ds1.Tables[0].Rows[a]["CT_LEVEL_ONE_ID"].ToString() + "'");
                sbRet.Append(",\"r_count\":" + arrrow1.Length.ToString() + ",rows:[");
                for (int b = 0; b < arrrow1.Length; b++)
                {
                    if (b > 0)
                    {
                        sbRet.Append(",");
                    }
                    sbRet.Append("{");
                    sbRet.Append("\"ID\":\"" + arrrow1[b]["CT_LEVEL_TWO_ID"].ToString() + "\"");
                    sbRet.Append(",\"NAME\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(arrrow1[b]["CT_LEVEL_TWO_NME"].ToString()) + "\"");

                    DataRow[] arrrow2 = ds3.Tables[0].Select("CT_LEVEL_TWO_ID='" + arrrow1[b]["CT_LEVEL_TWO_ID"].ToString() + "'");
                    sbRet.Append(",\"r_count\":" + arrrow2.Length.ToString() + ",rows:[");
                    for (int c = 0; c < arrrow2.Length; c++)
                    {
                        if (c > 0)
                        {
                            sbRet.Append(",");
                        }
                        sbRet.Append("{");
                        sbRet.Append("\"ID\":\"" + arrrow2[c]["CT_LEVEL_THREE_ID"].ToString() + "\"");
                        sbRet.Append(",\"NAME\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(arrrow2[c]["CT_LEVEL_THREE_NME"].ToString()) + "\"");

                        sbRet.Append(",\"r_count\":0,rows:[");

                        sbRet.Append("]");


                        sbRet.Append("}");
                    }


                    sbRet.Append("]");


                    sbRet.Append("}");
                }

                sbRet.Append("]");


                sbRet.Append("}");
            }
            sbRet.Append("]}");

            return sbRet.ToString();
        }


    }
}